#!/usr/bin/env python3

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
import subprocess
import schedule
import time

subject = "Python邮件测试"
sender = "m18503090587@163.com"
license_code = "EQg93sCjETcqJbuz"
receivers = ["m18503090587@163.com", "yanggan2015@foxmail.com"]

def get_ifconfig_output():
    # 执行 ifconfig 命令并获取输出
    result = subprocess.run(['ifconfig'], capture_output=True, text=True)
    return result.stdout

def send_email(subject, body, sender, license_code, receivers, smtp_host="smtp.163.com", smtp_port=25):
    try:
        mm = MIMEMultipart('related')
        mm["Subject"] = Header(subject, 'utf-8')
        mm["From"] = sender
        mm["To"] = ", ".join(receivers)

        message_text = MIMEText(body, "plain", "utf-8")
        mm.attach(message_text)

        stp = smtplib.SMTP()
        stp.connect(smtp_host, smtp_port)
        stp.set_debuglevel(1)
        stp.login(sender, license_code)
        stp.sendmail(sender, receivers, mm.as_string())
        print("邮件发送成功")
        stp.quit()
    except Exception as e:
        print(f"发送邮件时发生错误: {e}")

def job():
    ifconfig_output = get_ifconfig_output()
    send_email(subject, ifconfig_output, sender, license_code, receivers)

# 设置定时任务每天6点钟执行
schedule.every().day.at("06:00").do(job)

if __name__ == "__main__":
    while True:
        schedule.run_pending()
        time.sleep(1)